import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/**
 * 保持页面状态
 */
class MyApp20 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "BottomNavigationWidget",
      theme: ThemeData(primarySwatch: Colors.lightBlue),
      home: KeepAlive(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class KeepAlive extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return KeepAliveState();
  }
}

/*
with是dart的关键字，意思是混入的意思，
就是说可以将一个或者多个类的功能添加到自己的类无需继承这些类，避免多重继承导致的问题。
SingleTickerProviderStateMixin 主要是我们初始化TabController时，需要用到vsync ，垂直属性，然后传递this
*/
class KeepAliveState extends State<KeepAlive>
    with SingleTickerProviderStateMixin {
  TabController tabController;

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("KeepAlive"),
        bottom: TabBar(
          controller: tabController,
          tabs: [
            Tab(
              icon: Icon(Icons.directions_car),
            ),
            Tab(
              icon: Icon(Icons.directions_train),
            ),
            Tab(
              icon: Icon(Icons.directions_bike),
            )
          ],
        ),
      ),
      body: TabBarView(
        controller: tabController,
        children: [
          HomePage(),
          HomePage(),
          HomePage(),
        ],
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [Text("click me "), Text('$_count')],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        tooltip: 'Increment',
        child: Icon(
          Icons.add,
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
